package com.zmm.myyimixian.ui.activity.search.model;

import com.google.gson.Gson;
import com.zmm.myyimixian.bean.SearchBean;
import com.zmm.myyimixian.http.OkHttpClientUtils;

import java.io.IOException;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/10/24 0024.
 * 加载数据的接口实现层
 */

public class SearchModelImpl implements ISearchModel{
    @Override
    public void loadSearchBean(final String path, final OnLoadSearchBeanListener listener) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    //网络请求返回的数据
                    String json = OkHttpClientUtils.getStringFromUrl(path);
                    //传递最后的结果
                    subscriber.onNext(json);
                    subscriber.onCompleted();
                } catch (IOException e) {
                    e.printStackTrace();
                    subscriber.onError(e);//传递失败信息
                }
            }
        })
                .subscribeOn(Schedulers.newThread())//声明上面的网络请求在工作线程
                .observeOn(AndroidSchedulers.mainThread())//声明下面的工作是在UI线程
                .subscribe(new Action1<String>() {
                    @Override
                   public void call(String s) {
                        Gson gson = new Gson();
                        SearchBean searchBean = gson.fromJson(s,SearchBean.class);
                        listener.onSuccess(searchBean);  //将封装好的对象回调给访问网络成功的接口
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //将异常回调给访问网络失败的接口
                        listener.onFailure("网路异常",throwable );
                    }
                });
    }
}
